package lyux;

import java.io.IOException;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.URLEncoder;
import java.util.Scanner;

public class Client {
    private int port = 9999;
    private String host = "127.0.0.1";
    private Socket socket;
    private BufferedReader bufferedReader;
    private BufferedWriter bufferedWriter;

    public Client() {
        socket = new Socket();
        try {
            SocketAddress dest = new InetSocketAddress(this.host, this.port);
            socket.connect(dest);
            System.out.println("客户端已启动！");
            System.out.println("该客户端已绑定127.0.0.1:9999进程。");
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    public void sendGet(String path) throws IOException {

        if(path.equals(""))
            path = "/";

        OutputStreamWriter streamWriter = new OutputStreamWriter(socket.getOutputStream());
        bufferedWriter = new BufferedWriter(streamWriter);

        bufferedWriter.write("GET " + path + " HTTP/1.1\r\n");
        bufferedWriter.write("Host: " + this.host + "\r\n");
        bufferedWriter.write("Accept: */*\r\n");
        bufferedWriter.write("Accept-Language: en\r\n");
        bufferedWriter.write("Accept-Encoding: gzip, deflate\r\n");
        bufferedWriter.write("User-Agent: LyuxHttpClient\r\n");
        bufferedWriter.write("Connection: Keep-Alive\r\n");
        bufferedWriter.write("\r\n");
        bufferedWriter.flush();

        BufferedInputStream streamReader = new BufferedInputStream(socket.getInputStream());
        bufferedReader = new BufferedReader(new InputStreamReader(streamReader, "utf-8"));
        String line = null;
        System.out.println("================== Get Response From Server =================================");
        while ((line = bufferedReader.readLine()) != null) {
            System.out.println(line.toString());
        }
        System.out.println("========================================================================");
        //bufferedReader.close();
        //bufferedWriter.close();

    }

    public void sendPost(String path) throws IOException {

        if(path.equals(""))
            path = "/";

        String data = URLEncoder.encode("name", "utf-8") + "=" + URLEncoder.encode("lyux", "utf-8") + "&" + URLEncoder.encode("age", "utf-8") + "=" + URLEncoder.encode("23", "utf-8");


        OutputStreamWriter streamWriter = new OutputStreamWriter(socket.getOutputStream(), "utf-8");
        bufferedWriter = new BufferedWriter(streamWriter);

        bufferedWriter.write("POST " + path + " HTTP/1.1\r\n");
        bufferedWriter.write("Host: " + this.host + "\r\n");
        bufferedWriter.write("Content-Length: " + data.length() + "\r\n");
        bufferedWriter.write("Content-Type: application/x-www-form-urlencoded\r\n");
        bufferedWriter.write("Accept: */*\r\n");
        bufferedWriter.write("Accept-Language: en\r\n");
        bufferedWriter.write("Accept-Encoding: gzip, deflate\r\n");
        bufferedWriter.write("User-Agent: LyuxHttpClient\r\n");
        bufferedWriter.write("Connection: Keep-Alive\r\n");
        bufferedWriter.write("\r\n");
        bufferedWriter.write(data);

        bufferedWriter.write("\r\n");
        bufferedWriter.flush();

        BufferedInputStream streamReader = new BufferedInputStream(socket.getInputStream());
        bufferedReader = new BufferedReader(new InputStreamReader(streamReader, "utf-8"));
        String line = null;
        System.out.println("================== Post Response From Server =================================");
        while ((line = bufferedReader.readLine()) != null) {
            System.out.println(line.toString());
        }
        System.out.println("========================================================================");
        //bufferedReader.close();
        //bufferedWriter.close();

    }

    public static void main(String[] args) {
        Client td = new Client();
        Scanner in = new Scanner(System.in);
        System.out.println("请根据提示进行对服务器进行访问。");
        System.out.println("退出请输入代码：exit");


        System.out.println("请输入访问网址：");
        String url = in.next();
        if(url.equals("exit"))
            return;
        if(!url.substring(0,21).equals("http://127.0.0.1:9999")){
            System.out.println("请输入规定的协议或网址！");
            return;
        }

        String path = url.substring(url.lastIndexOf("127.0.0.1:9999")+14 );

        System.out.println("请输入想要请求数据的方式：GET/POST");
        String method = in.next();
        if(method.equals("exit"))
            return;

        try {
            if(method.equals("GET"))
                td.sendGet(path);
            else if(method.equals("POST"))
                td.sendPost(path);
            else{
                System.out.println("请求方法有限，请使用GET或POST方法请求数据，并重新输入命令。");

            }
        } catch (IOException e) {
            e.printStackTrace();
        }


        try{
            td.socket.close();
        }catch (IOException e){
            e.printStackTrace();
        }

    }
}
